package com.credithc.eagleeye.spring.starter;
import com.credithc.eagleeye.plugins.rabbitmq.EagleEyeSpringRabbitDecorator;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2019年10月24日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
public class EagleEyeRabbitBeanPostProcessor implements BeanPostProcessor {
    private final BeanFactory beanFactory;

    public EagleEyeRabbitBeanPostProcessor(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    private EagleEyeSpringRabbitDecorator eagleEyeSpringRabbitDecorator;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        if (bean instanceof RabbitTemplate) {
            return eagleEyeSpringRabbitDecorator().decorateBeforePublishRabbitTemplate((RabbitTemplate) bean);
        } else if (bean instanceof SimpleRabbitListenerContainerFactory) {
            return eagleEyeSpringRabbitDecorator().decorateSimpleRabbitListenerContainerFactory((SimpleRabbitListenerContainerFactory) bean);
        }else if (bean instanceof SimpleMessageListenerContainer) {
            return eagleEyeSpringRabbitDecorator().decorateSimpleRabbitListenerContainer((SimpleMessageListenerContainer) bean);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    private EagleEyeSpringRabbitDecorator eagleEyeSpringRabbitDecorator() {
        if (this.eagleEyeSpringRabbitDecorator == null) {
            this.eagleEyeSpringRabbitDecorator = this.beanFactory.getBean(EagleEyeSpringRabbitDecorator.class);
        }
        return this.eagleEyeSpringRabbitDecorator;
    }

}
